package com.xianwan;

import org.nutz.lang.Encoding;
import org.nutz.lang.Files;
import org.nutz.lang.Mirror;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;

import java.io.File;
import java.nio.charset.Charset;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;

/**
 * Created on 2017/11/19
 *
 * @author Jianghao(howechiang@gmail.com)
 */
public class MainSetup implements Setup {

    protected static final Log log = Logs.get();

    @Override
    public void init(NutConfig nutConfig) {

        if (!Charset.defaultCharset().name().equalsIgnoreCase(Encoding.UTF8)) {
            log.error("This project must run in UTF-8, pls add -Dfile.encoding=UTF-8 to JAVA_OPTS");
        }
        Files.clearDir(new File("~/tmp/00"));
    }

    @Override
    public void destroy(NutConfig nutConfig) {

        try {
            Mirror.me(Class.forName("com.mysql.jdbc.AbandonedConnectionCleanupThread")).invoke(null, "shutdown");
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }

        Enumeration<Driver> en = DriverManager.getDrivers();
        while (en.hasMoreElements()) {
            try {
                Driver driver = en.nextElement();
                String className = driver.getClass().getName();
                log.debug("deregisterDriver: " + className);
                DriverManager.deregisterDriver(driver);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}